<template>
  <div class="user-center">
    <!-- 搜索栏 -->
    <el-row :gutter="20" class="search-bar">
      <el-col :span="6">
        <el-input
            v-model="searchQuery"
            placeholder="输入用户名搜索"
            clearable
            @keyup.enter="handleSearch"
        />
      </el-col>
      <el-col :span="18">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="primary" @click="handleAdd">新增用户</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-col>
    </el-row>

    <!-- 用户列表 -->
    <el-table :data="tableData" style="width: 100%" v-loading="loading">
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="role" label="角色" />
      <el-table-column prop="created" label="创建时间">
        <template #default="scope">
          {{ formatDate(scope.row.created) }}
        </template>
      </el-table-column>
      <el-table-column prop="lastLogin" label="最后登录">
        <template #default="scope">
          {{ formatDate(scope.row.lastLogin) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
              size="small"
              type="primary"
              @click="handleResetPassword(scope.row)"
          >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-if="total > 0"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="handlePageChange"
    />

    <!-- 编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
        @close="handleDialogClose"
    >
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="教师" value="teacher" />
            <el-option label="学生" value="student" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
              v-model="form.status"
              :active-value="1"
              :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { formatDate } from '@/utils/format' // 假设你有一个日期格式化工具

const loading = ref(false)
const searchQuery = ref('')
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)

const form = reactive({
  id: null,
  username: '',
  email: '',
  role: '',
  status: 1
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const res = await axios.get(`/user/list?currentPage=${currentPage.value}`, {
      headers: {
        Authorization: localStorage.getItem('token')
      }
    })
    if (res.data.code === 200) {
      tableData.value = res.data.data.records
      total.value = res.data.data.total
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
// 搜索
const handleSearch = async () => {
  loading.value = true
  try {
    const res = await axios.get('/user/search', {
      params: {
        username: searchQuery.value,  // 搜索条件
        currentPage: 1,  // 重置到第一页
        pageSize: pageSize.value
      },
      headers: {
        Authorization: localStorage.getItem('token')
      }
    })
    if (res.data.code === 200) {
      tableData.value = res.data.data.records
      total.value = res.data.data.total
      currentPage.value = 1  // 更新当前页码
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = ''  // 清空搜索条件
  handleSearch()  // 重新搜索
}

// 新增用户
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  dialogVisible.value = true
  Object.assign(form, {
    id: null,
    username: '',
    email: '',
    role: '',
    status: 1
  })
}

// 编辑用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  dialogVisible.value = true
  Object.assign(form, row)
}

// 保存用户
const handleSave = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await axios.post('/user/save', form, {
          headers: {
            Authorization: localStorage.getItem('token')
          }
        })
        if (res.data.code === 200) {
          ElMessage.success('保存成功')
          dialogVisible.value = false
          fetchUsers()
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 修改状态
const handleStatusChange = async (row) => {
  try {
    const res = await axios.post('/user/status/change', {
      id: row.id,
      status: row.status
    }, {
      headers: {
        Authorization: localStorage.getItem('token')
      }
    })
    if (res.data.code === 200) {
      ElMessage.success('状态更新成功')
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

// 重置密码
const handleResetPassword = (row) => {
  ElMessageBox.confirm('确定要重置该用户的密码吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(async () => {
        try {
          const res = await axios.post(`/user/reset-password/${row.id}`, null, {
            headers: {
              Authorization: localStorage.getItem('token')
            }
          })
          if (res.data.code === 200) {
            ElMessage.success('密码重置成功')
          }
        } catch (error) {
          console.error('密码重置失败:', error)
          ElMessage.error('密码重置失败')
        }
      })
      .catch(() => {})
}

// 分页
const handlePageChange = (page) => {
  currentPage.value = page
  fetchUsers()
}

// 对话框关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-center {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>